package com.hy.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;

import com.hy.service.ValidateCodeService;
import com.hy.system.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ValidateCodeServiceImpl implements ValidateCodeService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 验证码图片缓存池大小
    private static final int CAPTCHA_POOL_SIZE = 20;

    // 验证码图片缓存池
    private static final CircleCaptcha[] CAPTCHA_POOL = new CircleCaptcha[CAPTCHA_POOL_SIZE];

    // 初始化验证码图片缓存池
    static {
        for (int i = 0; i < CAPTCHA_POOL_SIZE; i++) {
            CAPTCHA_POOL[i] = CaptchaUtil.createCircleCaptcha(150, 48, 4, 20);
        }
    }

    // 当前使用的验证码图片索引
    private static int currentIndex = 0;

    @Override
    public ValidateCodeVo generateValidateCode() {
        try {
            // 从缓存池中获取验证码图片
            CircleCaptcha circleCaptcha = CAPTCHA_POOL[currentIndex];

            // 更新索引
            currentIndex = (currentIndex + 1) % CAPTCHA_POOL_SIZE;

            // 生成新的验证码
            circleCaptcha.createCode();
            String codeValue = circleCaptcha.getCode();
            String imageBase64 = circleCaptcha.getImageBase64();

            // 生成uuid作为key
            String codeKey = UUID.randomUUID().toString().replace("-", "");
            String redisKey = "user:login:validatecode:" + codeKey;
            String redisValue = codeValue.toLowerCase();

            // 使用pipeline批量操作Redis
            redisTemplate.execute((RedisCallback<Object>) connection -> {
                connection.setEx(
                        redisKey.getBytes(),
                        300, // 5分钟过期
                        redisValue.getBytes()
                );
                return null;
            });

            // 构建响应对象
            ValidateCodeVo validateCodeVo = new ValidateCodeVo();
            validateCodeVo.setCodeKey(codeKey);
            validateCodeVo.setCodeValue("data:image/png;base64," + imageBase64);

            return validateCodeVo;
        } catch (Exception e) {
            log.error("生成验证码失败", e);
            throw new RuntimeException("验证码生成失败");
        }
    }
}
